package com.zkadmin.controller;

import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.zkadmin.entity.SysResource;
import com.zkadmin.service.SysResourceService;
import com.zkadmin.util.AdminConstants;

@SuppressWarnings("serial")
public class CreateResourceDialogCtrl extends BaseCtrl<Window> {

	@WireVariable
	private SysResourceService sysResourceService;

	@Wire
	private Window win;

	@Wire
	private Textbox name;
	@Wire
	private Textbox permission;
	@Wire
	private Textbox code;

	@Override
	protected void init(Window win) {
		this.win = win;
	}

	@Listen("onClick=#cancelBtn")
	public void closeDialog(Event e) {
		win.onClose();
	}

	@Listen("onClick=#okBtn")
	public void createRole(Event e) {
		if (sysResourceService.findByName(name.getValue()) != null) {
			throw new WrongValueException(name, "【" + name.getValue() + "】资源名称已经存在。");
		}

		if (sysResourceService.findByCode(code.getValue()) != null) {
			throw new WrongValueException(code, "【" + code.getValue() + "】资源代码已经存在。");
		}
		
		if (sysResourceService.findByCode(permission.getValue()) != null) {
			throw new WrongValueException(permission, "【" + permission.getValue() + "】资源权限标识已经存在。");
		}

		SysResource newResource = new SysResource();
		newResource.setCode(code.getValue());
		newResource.setName(name.getValue());
		newResource.setPermission(permission.getValue());
		sysResourceService.createPermission(newResource);
		Events.postEvent(AdminConstants.EVENT_ONREFRESH, win, null);
		win.onClose();
	}
}
